package com.github.icloudpay.pay.core.service.pay.alipay.service;

import java.math.BigDecimal;
import java.util.HashMap;
import java.util.Map;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import com.alipay.api.AlipayApiException;
import com.alipay.api.AlipayClient;
import com.alipay.api.DefaultAlipayClient;
import com.alipay.api.request.AlipayTradePrecreateRequest;
import com.alipay.api.response.AlipayTradePrecreateResponse;
import com.github.icloudpay.pay.core.feign.PayChannelConfigFeign;
import com.github.icloudpay.pay.core.inter.PayObjectService;
import com.github.icloudpay.pay.core.service.pay.alipay.util.AliPayConfig;
import com.github.wxiaoqi.security.common.admin.pay.request.OnlinePaymentRequest;
import com.github.wxiaoqi.security.common.msg.ResponseCode;
import com.github.wxiaoqi.security.common.util.EntityUtils;

import net.sf.json.JSONObject;

/**
 * 支付宝二维码支付
 * @author hexufeng
 *
 */
@Service("aliPreCreatService")
public class AliPreCreatService implements PayObjectService<OnlinePaymentRequest>{

	private static final Logger logger = LoggerFactory.getLogger(AliPreCreatService.class);

	@Autowired
	private PayChannelConfigFeign payChannelConfigFeign;
	@Autowired
    private AliPayConfig aliPayConfig;

	public Map<String, Object> pay(OnlinePaymentRequest request) {
		
		logger.info("****************调用支付宝二维码支付接口开始*******************");

		Map<String, Object> responseMap = new HashMap<String, Object>();

		Map<String, Object> reqMap = new HashMap<String, Object>();
    	reqMap.put("platformId", request.getPlatformId());
    	reqMap.put("merchantId", request.getMerchantId());
    	reqMap.put("payChannelNo", request.getPayChannelNo());
		Map<String, Object> respMap = payChannelConfigFeign.query(reqMap);
        if(!(boolean) respMap.get("success")){
			responseMap.put("success", false);
			responseMap.put("code", ResponseCode.PAYCHANNEL_CONFIGURATION_NOTEXIST.getCode());
			responseMap.put("msg", ResponseCode.PAYCHANNEL_CONFIGURATION_NOTEXIST.getMessage());
			return responseMap;
		}
        
        @SuppressWarnings("unchecked")
		Map<String, Object> configMap = (Map<String, Object>)respMap.get("payChannelConfigInfo");

		//商户订单号,64个字符以内、只能包含字母、数字、下划线；需保证在商户端不重复
		String out_trade_no = request.getSerialNo();

		//订单总金额，单位为元，精确到小数点后两位
		BigDecimal total_amount = request.getOrderAmt();

		//订单标题，粗略描述用户的支付目的。如“xxx品牌xxx门店消费”
		String subject = request.getProductName();

		JSONObject json = new JSONObject();
		json.put("out_trade_no", out_trade_no);
		json.put("total_amount", total_amount);
		json.put("subject", subject);
		String jsonStr = json.toString();
		logger.info("调用支付宝请求参数。。。。。。。{}", jsonStr);

		AlipayClient alipayClient = new DefaultAlipayClient("https://openapi.alipay.com/gateway.do",(String)configMap.get("outMerNo"),(String)configMap.get("outMerPrivateKey"),"json","UTF-8",(String)configMap.get("outMerPublicKey"),"RSA2");
		AlipayTradePrecreateRequest alipayRequest = new AlipayTradePrecreateRequest();
		alipayRequest.setNotifyUrl(aliPayConfig.getBackCallbackUrl() + "/callBack/aliPay");//支付回调地址
		alipayRequest.setBizContent(jsonStr);
		AlipayTradePrecreateResponse response;
		try {
			response = alipayClient.execute(alipayRequest);
			logger.info("调用支付宝响应参数。。。。。。。{}", EntityUtils.beanToMap(response));
			if(response.isSuccess() && "10000".equals(response.getCode())){
				if("ACQ.TRADE_HAS_SUCCESS".equals(response.getSubCode())){
					Map<String, Object> payMap = new HashMap<String, Object>();
					payMap.put("qr_code", response.getQrCode());//二维码
					responseMap.put("payInfo", payMap);//二维码
					responseMap.put("success", true);
					responseMap.put("code", ResponseCode.OK.getCode());
					responseMap.put("msg", ResponseCode.OK.getMessage());
					responseMap.put("scanCode", "0");//扫码支付标识，用于不做订单流水状态更新
				}else{
					responseMap.put("success", false);
					responseMap.put("code", ResponseCode.PAY_FAIL.getCode());
					responseMap.put("msg", ResponseCode.PAY_FAIL.getMessage());
				}
			} else {
				responseMap.put("success", false);
				responseMap.put("code", ResponseCode.SEND_DATA_FAIL.getCode());
				responseMap.put("msg", ResponseCode.SEND_DATA_FAIL.getMessage());
			}
		} catch (AlipayApiException e) {
			e.printStackTrace();
		}
		return responseMap;
	}

}
